package com.sunny.ynhz.ui.index;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.sunny.ynhz.R;
import com.sunny.ynhz.api.NetUrl;
import com.sunny.ynhz.utils.SPUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import io.rong.imkit.RongIM;


/**
 * Created by tangyunfei on 2017/9/1.
 */

public class GroupFragment extends Fragment {
    private View rootView;
    private RequestQueue mQueue;
    private ListView listView;
    private BaseAdapter mAdapter;
    private TextView addText;
    private ArrayList<HashMap<String,String>> datalist;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mQueue = Volley.newRequestQueue(getActivity());
        if(rootView == null){
            rootView = inflater.inflate(R.layout.fragment_group,container,false);
            initView();
            loadData();
        }
        return  rootView;
    }

    private void initView() {
        datalist = new ArrayList<>();
        listView = (ListView)rootView.findViewById(R.id.listView);
        mAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return datalist.size();
            }

            @Override
            public Object getItem(int position) {
                return position;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if(convertView == null){
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_msg_group,parent,false);
                }
                TextView title = (TextView)convertView.findViewById(R.id.id_name);
                title.setText(datalist.get(position).get("title"));
                TextView number = (TextView)convertView.findViewById(R.id.id_number);
                number.setText(datalist.get(position).get("number")+"人加入");
                return  convertView;
            }
        };
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("TAG","群ID："+ datalist.get(position).get("groupId"));
                RongIM.getInstance().startGroupChat(getActivity(),
                        datalist.get(position).get("groupId"),
                        datalist.get(position).get("title"));
            }
        });
    }

    protected void addGroup(final String title){
        long time=System.currentTimeMillis();
        String groupId = String.valueOf(time);
        String uid = SPUtil.get("userId","null").toString();
        Log.i("TAG","群ID"+groupId);
        String url = NetUrl.baseUrl+"rong/web/createGroup?userId="+uid+"&groupId="+groupId+"&groupName="+title;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if(status == 200){
                        datalist.clear();
                        loadData();
                    }else{
                        Toast.makeText(getActivity(),"创建群失败",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mQueue.add(stringRequest);
    }

    private void loadData() {
        String uid = SPUtil.get("userId","null").toString();
        String url =NetUrl.baseUrl+"rong/web/queryUserInGroup?userId="+uid;
        Log.i("TAG",url);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.i("TAG",response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = jsonObject.getInt("status");
                    if(status == 200){
                        JSONArray data = jsonObject.getJSONArray("result");
                        for (int i=0;i<data.length();i++){
                            JSONObject info = data.getJSONObject(i);
                            HashMap<String,String> hashMap = new HashMap<>();
                            hashMap.put("title",info.getString("title"));
                            hashMap.put("groupId",info.getString("groupId"));
                            hashMap.put("number",info.getString("number"));
                            datalist.add(hashMap);
                        }

                        mAdapter.notifyDataSetChanged();
                    }else{
                        TextView empty = new TextView(getActivity());
                        empty.setText("您还没有创建过群或加入群");
                        empty.setTextColor(Color.parseColor("#cccccc"));
                        empty.setHeight(100);
                        empty.setGravity(Gravity.CENTER);
                        listView.addHeaderView(empty);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        mQueue.add(stringRequest);

    }

}
